﻿package com.subumbo.audio.processing 
{
	
	/**
	* Simple 3 band EQ
	* @author leo@blixtsystems.com
	*/
	public class EQ 
	{
		// Enable/disable
		public var active:Boolean = false;
		
		// Gain Controls
		public var lg:Number = 1; 		// Low freq gain
		public var mg:Number = 1; 		// Mid freq gain
		public var hg:Number = 1; 		// Hi freq gain
		
		// Frequencies
		private var lowfreq:Number = 880; 	// Low crossover frequency
		private var hifreq:Number = 5000; 	// Hi crossover frequency
		
		// Filter #1 (Low band)
        private var f1p0:Number = 0; 	// 4 poles, should give 24dB/oct
        private var f1p1:Number = 0;
        private var f1p2:Number = 0;
        private var f1p3:Number = 0;
       
		// Filter #2 (High band)
        private var f2p1:Number = 0;
        private var f2p2:Number = 0;
        private var f2p0:Number = 0;
        private var f2p3:Number = 0;
        
		// Sample history buffer
        private var sdm1:Number = 0;
		private var sdm2:Number = 0;
        private var sdm3:Number = 0;
		
        private var lf:Number;
        private var hf:Number;
		
        static private const vsa:Number = 1.0 / 4294967295.0; // Very small amount (Denormal Fix)

        public function EQ() 
		{
            lg = 1;
            mg = 1;
            hg = 1;
            f1p0 = 0;
            f1p1 = 0;
            f1p2 = 0;
            f1p3 = 0;
            f2p0 = 0;
            f2p1 = 0;
            f2p2 = 0;
            f2p3 = 0;
            sdm1 = 0;
            sdm2 = 0;
            sdm3 = 0;
			// Calculate filter cutoff frequencies
            lf = 2 * Math.sin(Math.PI * (lowfreq / 44100));
            hf = 2 * Math.sin(Math.PI * (hifreq / 44100));
            return;
        }

        public function compute(sample:Number): Number 
		{
			// Low / Mid / High - Sample Values
			var l:Number;
			var m:Number;
			var h:Number;
			// Filter #1 (lowpass)
			f1p0 += (lf * (sample - f1p0));
			f1p1 += lf * (f1p0 - f1p1);
			f1p2 += lf * (f1p1 - f1p2);
			f1p3 += lf * (f1p2 - f1p3);
			l = f1p3;
			// Filter #2 (highpass)
			f2p0 += (hf * (sample - f2p0));
			f2p1 += hf * (f2p0 - f2p1);
			f2p2 += hf * (f2p1 - f2p2);
			f2p3 += hf * (f2p2 - f2p3);
			h = sdm3 - f2p3;
			// Calculate midrange (signal - (low + high))
			m = sdm3 - (l + h);
			// Scale, Combine and store
			l *= lg;
			m *= mg;
			h *= hg;
			// Shuffle history buffer
			sdm3 = sdm2;
			sdm2 = sdm1;
			sdm1 = sample;
			// Return result
			return l;
        }
		
	}
	
}